package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.DishDao;
import com.itheima.dao.SetmealDao;
import com.itheima.dto.SetmealDto;
import com.itheima.global.BusinessException;
import com.itheima.po.Dish;
import com.itheima.po.Setmeal;
import com.itheima.po.SetmealDish;
import com.itheima.service.DishServcie;
import com.itheima.service.SetmealDishServcie;
import com.itheima.service.SetmealServcie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author Andy
 * @Description //TODO EmployeeServiceImpl
 * @Date 2022/3/8 10:57 上午
 * @Version 1.0
 **/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealServcie {

    @Autowired
    private SetmealDishServcie setmealDishServcie;

    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //        1. 添加套餐
        this.save(setmealDto);
//        2 添加套餐与菜品关系
//        2.1 套餐菜品表中需要套餐的id，在套餐菜品实体中设置套餐的ID
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish :
                setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishServcie.saveBatch(setmealDishes);

    }

    @Transactional
    @Override
    public void deleteWithDish(List<Long> ids) {
        //    步骤 ids单个删除与批量删除
//    售卖中的套餐不能删除
//    所有要删除的套餐为停售状态，则删除套餐数据以及套餐菜品数据

        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId, ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus, 1);
        int countInSaling = this.count(lambdaQueryWrapper);
//        如果>0说明有套餐为启用状态，在售卖中
        if (countInSaling > 0){
            throw new BusinessException("有套餐在售卖中，无法删除，" +
                                                "请先将需要删除的所有套餐状态改为停售，然后再进行删除");
        }
//        根据IDs批量删除套餐
        this.removeByIds(ids);
//        根据套餐IDs批量套餐菜品数据
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishServcie.remove(setmealDishLambdaQueryWrapper);
    }
}
